package com.pd.backend.web.controller.net;

import com.pd.backend.common.R;
import com.pd.backend.common.utils.Base64;
import com.pd.backend.common.utils.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Producer;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码
 */
@RestController
@RequestMapping("/net/captcha")
@CrossOrigin
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    // 验证码类型
    private String captchaType = "math";

    @GetMapping("/captchaImage")
    public R captchaImage(HttpServletResponse response,String key) throws IOException {
        // 保存验证码信息
        // TODO  Constants   "captcha_codes:"
        String verifyKey = "captcha_codes:" + key;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        // TODO Contants CAPTCHA_EXPIRATION = 2
        redisCache.setCacheObject(verifyKey, code, 2, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return R.error(e.getMessage());
        }

        // TODO 返回一个流
        Map<String,String> map = new HashMap<>();
        map.put("key", key);
        map.put("img", Base64.encode(os.toByteArray()));
        R result = new R();
        result.setCode(200);
        result.setMsg("验证码获取成功");
        result.setMap(map);


        FileOutputStream write = new FileOutputStream(new File("D:/te111.jpg"));
        write.write(os.toByteArray());
        write.close();

        return result;
    }
}
